package ${projectPackage}.controller.${util.firstLower(table.javaName)};

import com.fasterxml.jackson.core.type.TypeReference;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.layout.Region;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.Function;
import java.util.Map;
import java.util.HashMap;
import org.apache.commons.beanutils.BeanUtils;
import ldh.common.PageResult;
import ldh.common.Pageable;
import ldh.fx.StageUtil;
import ldh.fx.component.LxDialog;
import ldh.fx.component.table.GridTable;
import ldh.fx.component.table.function.LoadData;
import ldh.fx.util.DialogUtil;

import ${pojoPackage}.${table.javaName};
<#list table.columnList as column>
    <#if util.isEnum(column)>
import ${enumProjectPackage}.${column.javaType};
    </#if>
</#list>
import ${projectPackage}.util.ConfigUtil;
import ${projectPackage}.util.JavafxHttpUtil;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.ResourceBundle;

public class ${table.javaName}MainController implements LoadData,  Initializable{

    @FXML private GridTable ${util.firstLower(table.javaName)}GridTable;

    private ${table.javaName}EditController ${util.firstLower(table.javaName)}EditController;
    private ${table.javaName}SearchController ${util.firstLower(table.javaName)}SearchController;

    private Map<String, Object> searchParam = new HashMap();

    public void addData(ActionEvent event) {
        Region region = loadFxml("/fxml/module/${util.firstLower(table.javaName)}/${table.javaName}EditForm.fxml", fxmlLoader -> {
            ${util.firstLower(table.javaName)}EditController = fxmlLoader.getController();
            ${util.firstLower(table.javaName)}EditController.set${table.javaName}MainController(this);
        });
        LxDialog ldhDialog = new LxDialog(StageUtil.STAGE, "add", region.getPrefWidth(), region.getPrefHeight());
        ldhDialog.setContentPane(region);
        ldhDialog.setStyle("-fx-padding: 2");
        ldhDialog.show();
    }

    public void editData(ActionEvent event) {
        TableView<${table.javaName}> tableView = ${util.firstLower(table.javaName)}GridTable.getTableView();
        ${table.javaName} selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem == null) {
            DialogUtil.info("提示", "请选择一行", 300, 120);
            return;
        }
        Region region = loadFxml("/fxml/module/${util.firstLower(table.javaName)}/${table.javaName}EditForm.fxml", fxmlLoader -> {
            ${util.firstLower(table.javaName)}EditController = fxmlLoader.getController();
            ${util.firstLower(table.javaName)}EditController.set${table.javaName}MainController(this);
        });
        ${util.firstLower(table.javaName)}EditController.setInitData(selectedItem);
        LxDialog ldhDialog = new LxDialog(StageUtil.STAGE, "修改", region.getPrefWidth(), region.getPrefHeight());
        ldhDialog.setContentPane(region);
        ldhDialog.setStyle("-fx-padding: 2");
        ldhDialog.show();
    }

    public void removeData(ActionEvent event) {
        TableView<${table.javaName}> tableView = ${util.firstLower(table.javaName)}GridTable.getTableView();
        ${table.javaName} selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem == null) {
            DialogUtil.info("提示", "请选择一行", 300, 120);
            return;
        }
    }

    public void searchData(ActionEvent event) {
        if (${util.firstLower(table.javaName)}SearchController == null) {
            Region region = loadFxml("/fxml/module/${util.firstLower(table.javaName)}/${table.javaName}SearchForm.fxml", fxmlLoader -> {
                ${util.firstLower(table.javaName)}SearchController = fxmlLoader.getController();
                ${util.firstLower(table.javaName)}SearchController.set${table.javaName}MainController(this);
            });
            ${util.firstLower(table.javaName)}GridTable.getMasterDetailPane().setDetailNode(region);
        }
        ${util.firstLower(table.javaName)}GridTable.expandPane();
    }

    public Region loadFxml(String fxml, Consumer<FXMLLoader> consumer) {
        Region region = null;
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation(this.getClass().getResource(fxml));
            region = fxmlLoader.load();
            consumer.accept(fxmlLoader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return region;
    }

    public void setSearchParam(Map<String, Object> searchParam) {
        this.searchParam = searchParam;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ${util.firstLower(table.javaName)}GridTable.setLoadData(this);
        load(null);
    }

    @Override
    public void load(Pageable pageable) {
        ${util.firstLower(table.javaName)}GridTable.getMaskerPane().setVisible(true);

        task(()->{
            PageResult<${table.javaName}> pageResult = loadPageResult(pageable);
            return null;
        });
    }

    private void loadingEnd(Task task) {
                ${util.firstLower(table.javaName)}GridTable.getMaskerPane().textProperty().unbind();
                ${util.firstLower(table.javaName)}GridTable.getMaskerPane().progressProperty().unbind();
                ${util.firstLower(table.javaName)}GridTable.getMaskerPane().setVisible(false);
        if (task.getException() != null) {
            task.getException().printStackTrace();
            Platform.runLater(()->DialogUtil.info("错误", task.getException().getMessage(), 300, 220));
        }
    }

    private PageResult<${table.javaName}> loadPageResult(Pageable pageable) {
        try {
            if (pageable != null) {
                searchParam.put("pageSize", pageable.getPageSize());
                searchParam.put("pageNo", pageable.getPageNo());
            }
            String url = ConfigUtil.getServerUrl() + "/${util.firstLower(table.javaName)}/list/json";
            PageResult<${table.javaName}> pageResult = JavafxHttpUtil.get(url, searchParam, new TypeReference<PageResult<${table.javaName}>>() {});
            Platform.runLater(()->${util.firstLower(table.javaName)}GridTable.setData(pageResult));
            return pageResult;
        } catch (Exception var2) {
            Platform.runLater(()->DialogUtil.info("查询数据失败", var2.getMessage(), 300, 220));
            return null;
        }
    }

    public void saveData(${table.javaName} ${util.firstLower(table.javaName)}, Function<?, ?> function) {
        task(()->{
            try {
                String url = ConfigUtil.getServerUrl() + "/${util.firstLower(table.javaName)}/save/json";
                Map paramMap = BeanUtils.describe(${util.firstLower(table.javaName)});
                JavafxHttpUtil.post(url, paramMap, Void.class);
                function.apply(null);
            } catch (Exception var2) {
                Platform.runLater(()->DialogUtil.info("保存数据失败", var2.getMessage(), 300, 220));
                return null;
            }

            ${table.javaName}MainController.this.loadPageResult((Pageable)null);
//            updateMessage("保存数据成功");
            return null;
        });
    }

    private void deleteData(${table.javaName} ${util.firstLower(table.javaName)}) {
        task(()->{
//          updateMessage("正在删除数据");

            try {
                ${table.primaryKey.column.javaType} id = ${util.firstLower(table.javaName)}.get${util.upFirst(table.primaryKey.column.property)}();
                String url = ConfigUtil.getServerUrl() + "/${util.firstLower(table.javaName)}/delete/" + id + "/json";
                JavafxHttpUtil.get(url, Void.class);
            } catch (Exception var2) {
                Platform.runLater(()->DialogUtil.info("删除数据失败", var2.getMessage(), 300, 220));
                return null;
            }

            ${table.javaName}MainController.this.loadPageResult((Pageable)null);
//           updateMessage("删除数据成功");
            return null;
        });
    }

    private void task(Supplier<?> supplier) {
        Task<Void> task = new Task() {
            @Override
            protected Void call() throws Exception {
                supplier.get();
                return null;
            }
        };
        task.setOnSucceeded(event -> {loadingEnd(task);});
        task.setOnFailed(event->{loadingEnd(task);});
        new Thread(task).start();
    }
}
